﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;
using System.Web.Configuration;

namespace WXYW
{
    public partial class ListProductNeedToDistribute : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindProduct();
            }
        }

        private void BindProduct()
        {
            ApplicationService service = new ApplicationService();
            ApplicationForm applicationForm = service.GetApplicationFormDetailByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));

            applyCompanyNameTxtBox.Text = applicationForm.User.FullName;
            mailAddressTxtBox.Text = applicationForm.User.UserAddress;
            applierEmailTxtBox.Text = applicationForm.User.UserEmail;
            applierFaxTxtBox.Text = applicationForm.User.UserFax;
            rmaLabel.Text = applicationForm.ApplicationCode;
            runningNumberLabel.Text = applicationForm.RunningNumber;
            receiveLabel.Text = applicationForm.ReceiveDateTime.HasValue ? applicationForm.ReceiveDateTime.Value.ToString("yyyy-MM-dd") : "";
            applierMobilePhoneTxtBox.Text = applicationForm.User.UserMobilePhone;
            applierNameTxtBox.Text = applicationForm.User.ContactPerson;
            applierPhoneTxtBox.Text = applicationForm.User.UserPhone;
            ProviderNameLbl.Text = applicationForm.ProviderName;
            statusLabel.Text = "待派单";

            productGridView.DataSource = applicationForm.ApplicationProduct;
            productGridView.DataBind();
            if (!applicationForm.ApplicationPicture.IsLoaded)
            {
                applicationForm.ApplicationPicture.Load();
            }
            List<ApplicationPicture> list = applicationForm.ApplicationPicture.Where(p => p.Type == (int)PictureType.ConfirmProduct).ToList();
            Table table = new Table();
            table.Rows.Add(new TableRow());
            table.Rows.Add(new TableRow());
            foreach (ApplicationPicture picture in list)
            {
                TableCell celllImage = new TableCell();
                Image imageControl = new Image();
                imageControl.Height = 100;
                imageControl.ImageUrl = "Picture/" + picture.PictureNameOnServer;
                imageControl.Attributes.Add("OnClick", "window.open('ImageDetail.aspx?Name=" + picture.PictureNameOnServer + "')");
                celllImage.Controls.Add(imageControl);
                table.Rows[0].Cells.Add(celllImage);

                TableCell cellName = new TableCell();
                Label label = new Label();
                label.Text = picture.PictureName;
                cellName.Controls.Add(label);
                table.Rows[1].Cells.Add(cellName);
            }
            picturePanel.Controls.Add(table);

            // for engineer work condition link
            if (!applicationForm.ServiceStationReference.IsLoaded)
            {
                applicationForm.ServiceStationReference.Load();
            }
            viewEngineerHyperLink.Attributes.Add("OnClick", "window.open('EngineerWorkCondition.aspx?" + Constants.QUERYSTR_STATION_ID + "=" + applicationForm.ServiceStation.ID + "')");
        }

        protected void productGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                ((Label)e.Row.FindControl("IDLbl")).Text = (e.Row.RowIndex + 1).ToString();

                LinkButton submitLinkButton = (LinkButton)e.Row.FindControl("submitLinkButton");
                submitLinkButton.CommandArgument = e.Row.DataItemIndex.ToString();

                LinkButton updatebutton = (LinkButton)e.Row.FindControl("updateLinkButton");
                updatebutton.CommandArgument = e.Row.DataItemIndex.ToString();

                ApplicationProduct product = e.Row.DataItem as ApplicationProduct;
                if (!product.UserReference.IsLoaded)
                {
                    product.UserReference.Load();
                }
                if (!product.ApplicationFormReference.IsLoaded)
                {
                    product.ApplicationFormReference.Load();
                }
                if (!product.ApplicationForm.ServiceStationReference.IsLoaded)
                {
                    product.ApplicationForm.ServiceStationReference.Load();
                }

                LinkButton serialNOButton = (LinkButton)e.Row.FindControl("serialNOLinkButton");
                serialNOButton.Text = product.ProductSerialNumber;

                UserService service = new UserService();
                DropDownList engineerDDL = (DropDownList)e.Row.FindControl("engineerDropDownList");
                engineerDDL.DataSource = service.GetEngineers(product.ApplicationForm.ServiceStation.ID);
                engineerDDL.DataTextField = "ContactPerson";
                engineerDDL.DataValueField = "UserID";
                engineerDDL.DataBind();
                if (product.User != null)
                {
                    engineerDDL.SelectedValue = product.User.UserID.ToString();
                }
                DropDownList repairTypeDDL = (DropDownList)e.Row.FindControl("repairTypeDropDownList");
                repairTypeDDL.Text = product.ProductRepairType;

                if (product.DistributeDateTime.HasValue)
                {
                    engineerDDL.Enabled = false;
                    repairTypeDDL.Enabled = false;
                    submitLinkButton.Enabled = false;
                }
            }
        }

        /// <summary>
        /// 点击“派单”按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void submitLinkButton_Click(object sender, EventArgs e)
        {
            string changeLogContent = string.Format("");
            ChangeLogService changeLogService = new ChangeLogService();

            try
            {
                int rowIndex = Convert.ToInt32(((LinkButton)sender).CommandArgument);
                DropDownList engineerDDL = ((DropDownList)productGridView.Rows[rowIndex].FindControl("engineerDropDownList"));
                int engineerID = Convert.ToInt32(engineerDDL.SelectedValue);

                if (engineerID > 0)
                {
                    long productID = long.Parse(productGridView.DataKeys[rowIndex].Value.ToString());
                    string repairType = ((DropDownList)productGridView.Rows[rowIndex].FindControl("repairTypeDropDownList")).Text;
                    TextBox butdatetext = ((TextBox)productGridView.Rows[rowIndex].FindControl("TextBox5"));
                    ApplicationProductService service = new ApplicationProductService();
                    service.DistributeApplicationProduct(productID, repairType, engineerID, Convert.ToDateTime(butdatetext.Text));

                    changeLogContent = string.Format("产品派单:维修工程师：{0}：：DistributeApplicationProduct", engineerID);
                    changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, productID.ToString(), changeLogContent); 

                    ApplicationService applicationService = new ApplicationService();
                    string code = applicationService.FinishDistributeForm(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));

                    changeLogContent = string.Format("产品派单:FinishDistributeFormt");
                    changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID], changeLogContent); 

                    BindProduct();

                    ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('此单已成功派给{0}维修。');", engineerDDL.SelectedItem.Text), true);
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('请选择您要将此单分配给哪位维修工程师。');", true);
                }
            }
            catch (Exception ex)
            {
                MsgLbl.Text = string.Format("系统错误:{0}", ex.Message);

                changeLogContent = string.Format("派单异常:ListProductNeedToDistribute.aspx submitLinkButton_Click {0}", ex.ToString());
                changeLogService.AddChangeLog(ChangeLogType.ApplicationForm, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID], changeLogContent); 
            }
        }

        protected void serialNOLinkButton_Click(object sender, EventArgs e)
        {
            LinkButton serialNOLinkButton = sender as LinkButton;
            serialNOLabel.Text = serialNOLinkButton.Text;
            ProductService service = new ProductService();
            ProductInfo pi = service.GetProductInfoBySerialNO(serialNOLinkButton.Text);
            if (pi != null)
            {
                saleUserLabel.Text = pi.JXSName;
                endtimeLabel.Text = pi.EndTime.HasValue ? pi.EndTime.Value.ToString("yyyy-MM-dd") : "";
                toLabel.Text = pi.SellTime.HasValue ? pi.SellTime.Value.ToString("yyyy-MM-dd") : "";
                informationLabel.Visible = false;
            }
            else
            {
                informationLabel.Visible = true;
                informationLabel.Text = "没有找到相关信息！";
                saleUserLabel.Text = "";
                endtimeLabel.Text = "";
                toLabel.Text = "";
            }

            notificationModalPopupExtender.Show();
        }

        protected void updateLinkButton_Click(object sender, EventArgs e)
        {
            int rowIndex = Convert.ToInt32(((LinkButton)sender).CommandArgument);
            DropDownList ddlengineer = (DropDownList)productGridView.Rows[rowIndex].FindControl("engineerDropDownList");
            LinkButton submitLinkButton = (LinkButton)productGridView.Rows[rowIndex].FindControl("submitLinkButton");
            ddlengineer.Enabled = true;
            submitLinkButton.Enabled = true;
            MsgLbl.Text = string.Empty;
        }

        protected void backLinkButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListFormNeedToDistribute.aspx");
        }

        protected void okLinkButton_Click(object sender, EventArgs e)
        {
            string changeLogContent = string.Format("");
            ChangeLogService changeLogService = new ChangeLogService();
            try
            {
                ApplicationProductService applicationProductService = new ApplicationProductService();
                foreach (GridViewRow row in productGridView.Rows)
                {
                    DropDownList engineerDDL = (DropDownList)row.FindControl("engineerDropDownList");
                    TextBox butdatetext = (TextBox)row.FindControl("TextBox5");
                    int engineerID = Convert.ToInt32(engineerDDL.SelectedValue);
                    if (engineerID > 0 && engineerDDL.Enabled)
                    {
                        long productID = long.Parse(productGridView.DataKeys[row.RowIndex].Value.ToString());
                        string repairType = ((DropDownList)productGridView.Rows[row.RowIndex].FindControl("repairTypeDropDownList")).Text;

                        applicationProductService.DistributeApplicationProduct(productID, repairType, engineerID, Convert.ToDateTime(butdatetext.Text));

                        changeLogContent = string.Format("产品派单:维修工程师：{0}：：DistributeApplicationProduct", engineerID);
                        changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, productID.ToString(), changeLogContent); 
                    }
                }               

                ApplicationService service = new ApplicationService();
                string code = service.FinishDistributeForm(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));

                changeLogContent = string.Format("产品派单:FinishDistributeForm");
                changeLogService.AddChangeLog(ChangeLogType.ApplicationProduct, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID], changeLogContent); 

                BindProduct();
                ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('您已经成功的派单，单号为：" + code + "');", true);
                SendAfterDistributeEmailToEngineer();
                MsgLbl.Text = "派单成功。";
          
                Response.Write(string.Format("<script language='JavaScript'> alert( '派单信息已成功保存！');location.href= 'ListFormNeedToDistribute.aspx' </script> "));
            }
            catch (Exception ex)
            {
                MsgLbl.Text = string.Format("系统错误:{0}", ex.Message);

                changeLogContent = string.Format("派单异常:ListProductNeedToDistribute.aspx okLinkButton_Click {0}", ex.ToString());
                changeLogService.AddChangeLog(ChangeLogType.ApplicationForm, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID], changeLogContent); 
            }
        }

        private void SendAfterDistributeEmailToEngineer()
        {
            string body = WebConfigurationManager.AppSettings["DistributeProduct"];
            ApplicationService service = new ApplicationService();
            ApplicationForm appform = service.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
            if (!appform.ApplicationProduct.IsLoaded)
            {
                appform.ApplicationProduct.Load();
            }
            foreach (ApplicationProduct product in appform.ApplicationProduct)
            {
                if (product != null)
                {
                    if (!product.UserReference.IsLoaded)
                    {
                        product.UserReference.Load();
                    }

                    if (product.User != null)
                    {
                        EmailService.SendEmail(product.User.UserEmail, "新的待修产品", string.Format(body, product.User.UserName));
                    }
                }
            }
        }
    }
}
